<template>
  <div class="my-project-layout flex w_100 h_100" ref="projectNavRef">
    <aside class="project_aside white sticky fontsize_14" :class="isFixed?'fix_bg':''">
      <div class="h_100" v-loading="projectLoading" :element-loading-spinner="loadingSvg" element-loading-text="加载中..."
        element-loading-background="rgba(0, 0, 0, 0.8)" element-loading-svg-view-box="0, 0, 50, 50">
        <header class="flex justify_between fontfamily_pingfang px_20 pb_20 base_border_bottom">
          <span class="font_bold ">我的分组</span>
          <i class="iconfont icon-Add cursor_point info_hover" @click="handleAddProject"></i>
        </header>
        <div class="flex_column">
          <div v-if="addingStatus"
            class="project_item cursor_point flex justify_between align_center mt_8 pl_50 pr_30 pb_0 pt_0 info_hover">
            <el-input type="primary" v-model.trim="projectModel.name" size="small"
              @keyup.native.enter.stop="addProjectAction()">
              <template #append><span class="white cursor_point" @click.stop="cancelProjectAdd()">取消</span>
              </template>
            </el-input>
          </div>
          <div v-for="(pro,idx) in projectList" :class="activeIdx===pro.project_id?'project_item_active':''" :key="idx"
            class="cursor_point pl_50 pr_30 pb_0 pt_0 info_hover">
            <div v-if="!pro.editing" @click="handleProjectItemClick(pro,idx)"
              class="project_item flex justify_between align_center">
              <span class="project_item_name">{{ pro.name }}</span>
              <i class="page_num fontfamily_stheiti block pr_6">{{ pro.num }}</i>
              <span class="project_op none">
                <i class="cursor_point iconfont icon-edit px_2" @click.stop="editProjectName(pro,idx)"></i>
                <i class="cursor_point iconfont icon-delete pl_2" @click.stop="handleDelProject(pro)"></i>
              </span>
            </div>
            <div class="project_item flex justify_between align_center" v-else>
              <el-input type="primary" v-model.trim="projectModel.name" size="small"
                @keyup.native.enter.stop="handleEditProjectName(pro)">
                <template #append><span class="white cursor_point" @click.stop="cancelProjectEdit(idx)">取消</span>
                </template>
              </el-input>
            </div>
          </div>
        </div>
      </div>
    </aside>
    <main class="project_main">
      <my-page v-if="project_id" :project_id="project_id" @deletepage="deletepage"></my-page>
    </main>
  </div>
</template>

<script>
import {
  defineAsyncComponent,
  defineComponent,
  onMounted,
  onUnmounted,
  ref,
} from "vue";
import {
  addProject,
  deleteProject,
  editProjectNameById,
  getProjectList,
} from "../../service/project";
import { loadingSvg } from "../../utils/constant";
import { cloneDeep } from "lodash-es";

const MyPage = defineAsyncComponent(() => import("./my-page.vue"));

export default defineComponent({
  name: "my-project",
  components: { MyPage },
  setup(prop, ctx) {
    const query = ref({
      name: "",
    });
    const projectNavRef = ref(null);
    const isFixed = ref(false);
    const project_id = ref(null);
    const projectLoading = ref(false);
    const projectList = ref([]);
    const projectName = ref("");
    const editFlag = ref(false);
    const activeIdx = ref(-1);
    const selectId = ref(null);
    const projectModel = ref({ name: "" });
    const addingStatus = ref(false);
    const getList = () => {
      projectLoading.value = false;
      getProjectList(query.value)
        .then((res) => {
          projectList.value = res.data.result;
          projectLoading.value = false;
          if (projectList.value.length) {
            activeIdx.value === -1
              ? (activeIdx.value = projectList.value[0].project_id)
              : activeIdx.value;
            handleProjectItemClick(projectList.value[0]);
          }
        })
        .catch(() => {
          projectLoading.value = false;
        });
    };
    const handleAddProject = (e) => {
      if (addingStatus.value) {
        return;
      }
      projectModel.value = {
        name: "",
      };
      addingStatus.value = true;
    };
    const addProjectAction = () => {
      addProject(projectModel.value)
        .then(() => {
          ElMessage({
            type: "success",
            message: "新增项目成功",
          });
          projectModel.value.name = "";
          addingStatus.value = false;
          getList();
        })
        .catch(() => {});
    };
    const editProjectName = (project, idx) => {
      projectModel.value = {
        name: "",
      };
      projectList.value[idx].editing = true;
      projectModel.value = cloneDeep(project);
      selectId.value = project.project_id;
    };
    const cancelProjectEdit = (idx) => {
      projectList.value[idx].editing = false;
    };
    const handleEditProjectName = () => {
      editProjectNameById(projectModel.value)
        .then((res) => {
          ElMessage({
            type: "success",
            message: "修改项目成功",
          });
          getList();
          editFlag.value = false;
        })
        .catch((err) => {
          ElMessage.error(err.message);
        });
    };
    const deletepage = (project_id) => {
      projectList.value.map((item) => {
        if (item.project_id === project_id) {
          item.num--;
        }
        return item;
      });
    };
    const cancelProjectAdd = () => {
      addingStatus.value = false;
    };
    const handleDelProject = (pro) => {
      ElMessageBox.confirm("你确定删除当前项目?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        projectLoading.value = true;
        deleteProject({ project_id: pro.project_id })
          .then(() => {
            if (activeIdx.value === pro.project_id) {
              activeIdx.value = -1;
            }
            ElMessage({
              type: "success",
              message: "删除项目成功",
            });
            getList();
          })
          .catch((err) => {
            projectLoading.value = false;
            ElMessage.error(err.message);
          });
      });
    };
    const handleProjectItemClick = (pro, idx) => {
      activeIdx.value = pro.project_id;
      project_id.value = pro.project_id;
    };
    const scroll = () => {
      isFixed.value = projectNavRef.value.offsetTop > 320;
    };
    onMounted(() => {
      getList();
      window.addEventListener("scroll", scroll);
    });
    onUnmounted(() => {
      window.removeEventListener("scroll", scroll);
    });
    return {
      query,
      isFixed,
      project_id,
      projectLoading,
      projectList,
      projectName,
      editFlag,
      selectId,
      activeIdx,
      projectModel,
      addingStatus,
      projectNavRef,
      cancelProjectAdd,
      addProjectAction,
      handleAddProject,
      handleEditProjectName,
      editProjectName,
      cancelProjectEdit,
      handleDelProject,
      getList,
      handleProjectItemClick,
      loadingSvg: loadingSvg,
      deletepage,
    };
  },
});
</script>

<style lang="less" scoped>
@import "project";

.upload-csv {
  font-size: 44px;
}
</style>
